package com.doubao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.doubao.entity.ChatMessage;
import com.doubao.entity.SmartDevice;
import com.doubao.entity.vo.ChatMessageVO;
import com.doubao.exception.BusinessException;
import com.doubao.mapper.ChatMessageMapper;
import com.doubao.service.ChatMessageService;
import com.doubao.service.SmartDeviceService;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionRequest;
import com.volcengine.ark.runtime.model.completion.chat.ChatCompletionResult;
import com.volcengine.ark.runtime.model.completion.chat.ChatMessageRole;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.List;
import com.volcengine.ark.runtime.model.completion.chat.*;
import com.volcengine.ark.runtime.service.ArkService;

@Slf4j
@Service
@RequiredArgsConstructor
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage> implements ChatMessageService {

        private final SmartDeviceService smartDeviceService;
    private final ArkService arkService;
    private static final int MAX_MESSAGE_LENGTH = 4000;
    private static final int MAX_HISTORY_TURNS = 10;

       @Override
   @Transactional(rollbackFor = Exception.class)
   public ChatMessageVO sendMessage(Long userId, Long deviceId, String content) {
       // 参数校验
       validateMessageParams(content);

       // 获取智能体信息并检查权限
       SmartDevice device = checkAndGetDevice(userId, deviceId);

       try {
           // 获取历史消息
           List<ChatMessage> history = getMessageHistory(userId, deviceId);

           // 构建完整的消息列表
           List<com.volcengine.ark.runtime.model.completion.chat.ChatMessage> messages = new ArrayList<>();

           // 添加系统消息
           messages.add(com.volcengine.ark.runtime.model.completion.chat.ChatMessage.builder()
                   .role(ChatMessageRole.SYSTEM)
                   .content("你是豆包，是由字节跳动开发的 AI 人工智能助手。请记住用户之前说过的话，保持对话连贯。")
                   .build());

           // 添加历史消息
           messages.addAll(convertToChatMessages(history));

           // 添加新的用户消息
           com.volcengine.ark.runtime.model.completion.chat.ChatMessage userMessage = com.volcengine.ark.runtime.model.completion.chat.ChatMessage.builder()
                   .role(ChatMessageRole.USER)
                   .content(content)
                   .build();
           messages.add(userMessage);

           // 创建请求
           ChatCompletionRequest chatRequest = ChatCompletionRequest.builder()
                   .model(device.getModelEndpointId())
                   .messages(messages)
                   .build();

           // 调用AI服务
           ChatCompletionResult result = arkService.createChatCompletion(chatRequest);

           if (result != null && result.getChoices() != null && !result.getChoices().isEmpty()) {
               ChatCompletionChoice choice = result.getChoices().get(0);
               com.volcengine.ark.runtime.model.completion.chat.ChatMessage assistantMessage = choice.getMessage();
               String reply = (String) assistantMessage.getContent();

               // 保存用户消息和AI回复到数据库
               ChatMessage dbUserMessage = saveUserMessage(userId, deviceId, content);
               ChatMessage dbAiMessage = saveAiMessage(userId, deviceId, reply, dbUserMessage.getId());

               // 更新对话统计
               updateChatStatistics(deviceId);

               return convertToVO(dbAiMessage, device);
           }

           throw new BusinessException("AI服务返回为空");

       } catch (Exception e) {
           log.error("发送消息失败: userId={}, deviceId={}", userId, deviceId, e);
           throw new BusinessException("发送消息失败: " + e.getMessage());
       }
   }


    /**
     * 转换数据库消息到Chat消息
     */
    private List<com.volcengine.ark.runtime.model.completion.chat.ChatMessage> convertToChatMessages(List<ChatMessage> dbMessages) {
        List<com.volcengine.ark.runtime.model.completion.chat.ChatMessage> chatMessages = new ArrayList<>();
        for (ChatMessage dbMessage : dbMessages) {
            ChatMessageRole role = "user".equals(dbMessage.getRole()) ?
                ChatMessageRole.USER : ChatMessageRole.ASSISTANT;

            chatMessages.add(com.volcengine.ark.runtime.model.completion.chat.ChatMessage.builder()
                    .role(role)
                    .content(dbMessage.getContent())
                    .build());
        }
        return chatMessages;
    }

    /**
     * 获取历史消息
     */
    private List<ChatMessage> getMessageHistory(Long userId, Long deviceId) {
        return lambdaQuery()
                .eq(ChatMessage::getUserId, userId)
                .eq(ChatMessage::getDeviceId, deviceId)
                .eq(ChatMessage::getStatus, 1)
                .orderByDesc(ChatMessage::getId)
                .last("LIMIT " + MAX_HISTORY_TURNS * 2)
                .list();
    }

    @Override
    public IPage<ChatMessageVO> pageMessages(Long userId, Long deviceId, Page<ChatMessage> page) {
        // 检查访问权限
        smartDeviceService.checkDeviceAccess(userId, deviceId);

        return baseMapper.selectMessagePage(page, userId, deviceId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteMessage(Long userId, Long messageId) {
        ChatMessage message = getById(messageId);
        if (message == null || !message.getUserId().equals(userId)) {
            throw new BusinessException("无权删除该消息");
        }

        // 逻辑删除消息
        message.setStatus(0);
        updateById(message);

        // 如果存在子消息，也需要删除
        lambdaUpdate()
                .eq(ChatMessage::getParentId, messageId)
                .set(ChatMessage::getStatus, 0)
                .update();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void clearChat(Long userId, Long deviceId) {
        // 检查权限
        smartDeviceService.checkDeviceAccess(userId, deviceId);

        // 批量逻辑删除消息
        lambdaUpdate()
                .eq(ChatMessage::getUserId, userId)
                .eq(ChatMessage::getDeviceId, deviceId)
                .set(ChatMessage::getStatus, 0)
                .update();
    }

    private void validateMessageParams(String content) {
        if (content == null || content.trim().isEmpty()) {
            throw new BusinessException("消息内容不能为空");
        }
        if (content.length() > MAX_MESSAGE_LENGTH) {
            throw new BusinessException("消息内容过长，最大支持" + MAX_MESSAGE_LENGTH + "个字符");
        }
    }

    private SmartDevice checkAndGetDevice(Long userId, Long deviceId) {
        SmartDevice device = smartDeviceService.getById(deviceId);
        if (device == null) {
            throw new BusinessException("智能体不存在");
        }
        smartDeviceService.checkDeviceAccess(userId, deviceId);
        return device;
    }

    private ChatMessage saveUserMessage(Long userId, Long deviceId, String content) {
        ChatMessage message = new ChatMessage();
        message.setUserId(userId);
        message.setDeviceId(deviceId);
        message.setContent(content);
        message.setRole("user");
        message.setStatus(1);
        save(message);
        return message;
    }

    private ChatMessage saveAiMessage(Long userId, Long deviceId, String content, Long parentId) {
        ChatMessage message = new ChatMessage();
        message.setUserId(userId);
        message.setDeviceId(deviceId);
        message.setContent(content);
        message.setRole("assistant");
        message.setParentId(parentId);
        message.setStatus(1);
        save(message);
        return message;
    }

    private void updateChatStatistics(Long deviceId) {
        smartDeviceService.lambdaUpdate()
                .setSql("chat_count = chat_count + 1")
                .eq(SmartDevice::getId, deviceId)
                .update();
    }

    private ChatMessageVO convertToVO(ChatMessage message, SmartDevice device) {
        ChatMessageVO vo = new ChatMessageVO();
        vo.setId(message.getId());
        vo.setContent(message.getContent());
        vo.setRole(message.getRole());
        vo.setCreatedAt(message.getCreatedAt());

        if ("assistant".equals(message.getRole())) {
            vo.setSenderName(device.getName());
            vo.setSenderAvatar(device.getIcon());
        }

        return vo;
    }

   private List<com.volcengine.ark.runtime.model.completion.chat.ChatMessage> convertToDoubaoMessages(List<ChatMessage> messages) {
       return messages.stream()
               .map(msg -> com.volcengine.ark.runtime.model.completion.chat.ChatMessage.builder()
                       .role(convertRole(msg.getRole()))
                       .content(msg.getContent())
                       .build())
               .collect(java.util.stream.Collectors.toList());
   }

   private ChatMessageRole convertRole(String role) {
       switch (role) {
           case "user":
               return ChatMessageRole.USER;
           case "assistant":
               return ChatMessageRole.ASSISTANT;
           default:
               throw new IllegalArgumentException("未知的角色: " + role);
       }
   }

}